package com.dayatang.product.webapp.action.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dayatang.domain.QuerySettings;
import com.dayatang.product.domain.Product;
import com.dayatang.product.domain.ProductTrial;
import com.dayatang.product.domain.TrialStatus;
import com.dayatang.product.domain.Visit;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.annotation.PMLog;

public class ProductUseManageAction extends BaseAction {

	private static final long serialVersionUID = -932706206458458864L;

	private TrialStatus status;
	
	private Product product;
	
	private List<ProductTrial> productTrials;
	
	@PMLog(moduleName="产品管理",option="使用情况")
	public String execute() throws Exception {
		
		QuerySettings<ProductTrial> querySettings = QuerySettings.create(ProductTrial.class);
		if (product != null && status != null) {
			product = Product.get(Product.class, product.getId());
			querySettings.eq("product", product).eq("status", status);
			page.setUrl("product-use-manage.action?product.id=" + product.getId() + "&status=" + status + "&");
		} else if (product != null) {
			product = Product.get(Product.class, product.getId());
			querySettings.eq("product", product);
			page.setUrl("product-use-manage.action?product.id=" + product.getId() + "&");
		} else if (status != null) {
			querySettings.eq("status", status);
			page.setUrl("product-use-manage.action?status=" + status + "&");
		} else {
			querySettings.desc("trialCode.registerDate");
			page.setUrl("product-use-manage.action?");
		}
		page.setDataTotal(ProductTrial.findByQuerySettings(querySettings).size());
		
		navBar = "产品管理  → 使用情况";
		querySettings.setFirstResult(page.getFirstResult()).setMaxResults(page.getPageSize());
		productTrials = ProductTrial.findByQuerySettings(querySettings);
		
		return SUCCESS;
	}
	
	public List<ProductTrial> getProductTrials() {
		return productTrials;
	}

	public void setProductTrials(List<ProductTrial> productTrials) {
		this.productTrials = productTrials;
	}

	public TrialStatus getStatus() {
		return status;
	}

	public void setStatus(TrialStatus status) {
		this.status = status;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public Map<TrialStatus, String> getStatusMap() {
		Map<TrialStatus, String> map = new HashMap<TrialStatus, String>();
		for (TrialStatus status : TrialStatus.values()) {
			map.put(status, getText(status.toString()));
		}
		return map;
	}
	
	public static long getVisitAmount(ProductTrial productTrial) {
		List<Visit> visits = Visit.findByProductTrialAlreadyVisit(productTrial);
		return visits.size() > 0 ? visits.size() : 0;
	}

}
